import React, { useContext, useState } from "react";
import classNames from "classnames";
// import { CSSTransition } from "react-transition-group";
import { MenuContext } from "./menu.tsx";
import { IMenuItemProps } from './menuItem.tsx';
import Icon from "../Icon/icon.tsx";
import Transition from "../Transition/transition.tsx";

export interface ISubMenuProps {
    index?: string;
    title: string;
    className?: string;
    children?: React.ReactNode;
}

const SubMenu: React.FC<ISubMenuProps> = (props) => {
    const { index, title, className, children } = props;
    const context = useContext(MenuContext);
    const openedSubMenus = context.defaultOpenSubMenus as Array<string>;
    const isOpened = (index && context.mode === "vertical") ? openedSubMenus.includes(index) : false;
    const [menuOpen, setMenuOpen] = useState<boolean>(isOpened); // 控制下拉
    const classes = classNames("menu-item submenu-item", className, {
        "is-active": context.index === index,
        "is-opened": menuOpen,
        "is-vertical": context.mode === "vertical"
    });
    // 纵向点击展开
    const handleClick = (e: React.MouseEvent) => {
        e.preventDefault();
        // 点击下拉菜单
        setMenuOpen(!menuOpen);
    }
    // 横向hover展开
    let timer: any;
    const handleHover = (e: React.MouseEvent, toggle: boolean) => {
        e.preventDefault();
        clearTimeout(timer);
        timer = setTimeout(() => {
            setMenuOpen(toggle);
        }, 80);
    }
    const clickEvent = context.mode === "vertical" ? {
        onClick: handleClick
    } : {};
    const hoverEvent = context.mode === "horizontal" ? {
        onMouseEnter: (e: React.MouseEvent) => { handleHover(e, true) },
        onMouseLeave: (e: React.MouseEvent) => { handleHover(e, false) }
    } : {}

    const renderChildren = () => {
        const subMenuClass = classNames("menu-submenu", {
            "menu-opened": menuOpen
        });
        const childrenComponent = React.Children.map(children, (child, i) => {
            const childElement = child as React.FunctionComponentElement<IMenuItemProps>;
            if (childElement.type.displayName === 'MenuItem' || childElement.type.displayName === 'SubMenu') {
                return React.cloneElement(childElement, { index: `${index}-${i}` });
            } else {
                console.error("SubMenu的子元素必须是MenuItem类型!");
            }
        });
        return (
            <Transition in={menuOpen} timeout={ 300 } animation="zoom-in-top" >
                <ul className={subMenuClass}>{childrenComponent}</ul>
            </Transition>
            
        );
    }

    return (
        <li key={index} className={classes} {...hoverEvent}>
            <div className="submenu-title" {...clickEvent}>
                {title}
                <Icon icon="angle-down" className="arrow-icon"></Icon>
            </div>
            {renderChildren()}
        </li>
    );
}
SubMenu.displayName = "SubMenu";
export default SubMenu;